package threshold;

/**
 * @Author wujiaming
 * @Description TODO
 * @Date 2023-02-01 17:40
 * @Version 1.0
 * 给定一个 n 个元素有序的（升序）整型数组 nums 和一个目标值 target  ，写一个函数搜索 nums 中的 target，如果目标值存在返回下标，否则返回 -1。
 */
public class BinSearch {

    /**
     * 非递归算法
     * @param nums
     * @param target
     * @return
     */
    public int search(int[] nums,int target){
        int low = 0,high = nums.length-1;
        int mid;
        while(low <= high){
            mid = (low + high)/2;
            if(nums[mid]== target){
                return mid;
            }else if(nums[mid]<target){
                low =mid+1;
            }else{
                high = mid-1;
            }
        }
        return -1;
    }

    public int recurSearch(int[] nums, int target, int low, int high) {

        int mid = (low + high) / 2;
        if (nums[mid] == target) {
            return mid;
        } else if (nums[mid] < target) {
            recurSearch(nums, target, mid + 1, high);
        } else {
            recurSearch(nums, target, low, mid - 1);
        }
        return 0;
    }

    public static void main(String[] args) {
        BinSearch binSearch = new BinSearch();
        int[] nums = {5};
        System.out.println(binSearch.search(nums,5));

    }
}
